import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import {
  Row,
  Col,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Collapse,
  DatePicker,
  PageHeader,
} from 'antd';
import prompt from '@/components/Prompt';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import AntdUpload from '@/components/AntdUpload';
import SearchSelect from '@/components/SearchSelect';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import { columns1 } from '@/pages/Common/common';
import styles from '@/pages/Operate.less';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const Panel = Collapse.Panel;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
@connect(({ manageEtc, common, loading }) => ({
  manageEtc,
  ownCompany: common.ownCompany,
  dictObject: common.dictObject,
  // id: manageEtc.id,
  loading: loading.effects['manageEtc/etcDetails'],
}))
@Form.create()
export default class ETCOperate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      currentId: '',
      selectedRows: [],
      visible: false,
      fileList: [],
      activeKey: ['1'],
      deleteFileIds: [],
      cars: [],
      ownCompany: '',
      disabled: false,
    };
  }
  componentDidMount() {
    const { match, form, dispatch } = this.props;
    const ID = match && match.params ? match.params.id : '';
    this.setState({
      currentId: ID,
    });
    if (ID) {
      this.getSelectDetails(ID);
    } else {
      form.resetFields();
    }
    // 查询字典：
    //币种：
    dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'currency-type' },
    });
  }
  //详情信息：
  getSelectDetails = ID => {
    this.props.dispatch({
      type: 'manageEtc/etcDetails',
      payload: { id: ID },
      callback: data => {
        if (!data) return;
        this.setFileList(data.attachments);
        this.setState({ cars: [{ id: data.vehicleId }] });
      },
    });
  };

  setFileList = list => {
    this.setState({ fileList: list });
  };

  callback = key => {
    this.setState({
      activeKey: key,
    });
  };
  //图片上传end：

  // 上传图片
  handleChange = fileList => {
    this.setState({ fileList });
  };

  // 删除图片
  onRemove = deleteFileIds => {
    this.setState({
      deleteFileIds,
    });
  };
  getValue = values => {
    this.setState({
      cars: values,
    });
    values.map(v => {
      this.setState({
        ownCompany: v.ownCompanyName,
      });
    });
  };

  operatePaneButton = e => {
    e.stopPropagation();
    e.preventDefault();

    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { purchaseDate, ...value } = values;
        const { fileList, deleteFileIds, cars } = this.state;
        //保存车辆
        if (cars.length > 0) {
          const vehicleId = cars.map(v => {
            return v.id;
          });
          value.vehicleId = vehicleId.join(',');
        } else {
          value.vehicleId = '';
        }
        if (purchaseDate) {
          value.purchaseDate = moment(purchaseDate).format(dateFormat);
        }
        const {
          match: { params },
          dispatch,
        } = this.props;
        if (params.id) {
          value.id = params.id;
          dispatch({
            type: 'manageEtc/EtcOperate',
            payload: value,
            callback: () => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              this.dispatchFun('manageEtc/ETCList', {});
            },
          });
        } else {
          dispatch({
            type: 'manageEtc/EtcOperate',
            payload: value,
            callback: res => {
              if (!res) return;
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              dispatch({
                type: 'manageEtc/etcDetails',
                payload: { id: res },
                callback: data => {
                  //新增变编辑页面：
                  dispatch({
                    type: 'common/setTabsName',
                    payload: {
                      id: res,
                      name: data.cardNo,
                      isReplaceTab: true,
                    },
                    callback: result => {
                      if (result) {
                        router.push(`/carBasic/manageEtc/ETCList/editETC/${res}`);
                      }
                    },
                  });
                },
              });
              this.dispatchFun('manageEtc/ETCList', {});
            },
          });
        }
      }
    });
  };
  // dispatch 方法
  dispatchFun(type, params) {
    const { dispatch } = this.props;
    dispatch({
      type: type,
      payload: params,
    });
  }

  render() {
    const {
      selectedRowKeys,
      selectedRows,
      visible,
      previewImage,
      fileList,
      papersDetails,
      ownCompany,
      cars,
      disabled,
    } = this.state;
    const {
      manageEtc: { etcDetails },
      form: { getFieldDecorator },
      dictObject,
      match: { params },
      showType,
    } = this.props;
    const currentId = params.id;
    let selectDetails = etcDetails[currentId];
    console.log('selectDetails===', selectDetails);

    const checkDisabled = selectDetails && Object.keys(selectDetails).length > 0 ? true : false;

    const vehicleList = [];
    const genExtraBasicInfo = () => (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span>{selectDetails && currentId ? selectDetails.cardNo : '新增ETC'}</span>
        {disabled ? (
          <AdButton
            type="primary"
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="编辑"
            code={selectDetails && currentId ? codes.edit : codes.add}
          />
        ) : (
          <Button.Group>
            <AdButton
              type="primary"
              onClick={e => this.operatePaneButton(e)}
              text="保存"
              code={selectDetails && currentId ? codes.edit : codes.add}
            />
            {selectDetails && currentId && (
              <AdButton
                onClick={() => {
                  this.setState(preState => ({
                    disabled: !preState.disabled,
                  }));
                }}
                text="取消"
                code={selectDetails && currentId ? codes.edit : codes.add}
              />
            )}
          </Button.Group>
        )}
      </div>
    );
    const customPanelStyle = {
      borderRadius: 4,
      marginBottom: 12,
      border: 0,
      overflow: 'hidden',
    };
    const prefixSelector = getFieldDecorator('currencyType', {
      initialValue: 'CNY',
    })(
      <Select placeholder="请选择" disabled={disabled || checkDisabled}>
        {dictObject['currency-type'] &&
          dictObject['currency-type'].map(item => <Option key={item.code}>{item.value}</Option>)}
      </Select>
    );

    const _gutter = { md: 8, lg: 24, xl: 48 };
    const _col = { md: 12, sm: 24 };
    const _row = { md: 24 };

    return (
      <div className={styles.CollapseUpdate}>
        <PageHeaderWrapper title={genExtraBasicInfo()}>
          <Collapse
            activeKey={this.state.activeKey}
            onChange={key => this.callback(key)}
            bordered={false}
          >
            <Panel header="ETC信息" key="1" style={customPanelStyle}>
              <div className={styles.tableListForm}>
                <Form layout="inline">
                  <Row gutter={_gutter}>
                    <Col {..._col}>
                      <Form.Item label="卡号">
                        {getFieldDecorator('cardNo', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: selectDetails ? selectDetails.cardNo : '',
                        })(<Input placeholder="请输入" disabled={disabled || checkDisabled} />)}
                      </Form.Item>
                    </Col>
                    <Col {..._col}>
                      <Form.Item label="购买日期">
                        {getFieldDecorator('purchaseDate', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue:
                            selectDetails && selectDetails.purchaseDate
                              ? moment(selectDetails.purchaseDate, dateFormat)
                              : '',
                        })(
                          <DatePicker
                            style={{ width: '100%' }}
                            disabled={disabled || checkDisabled}
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={_gutter}>
                    <Col {..._col}>
                      <Form.Item label="车牌号">
                        {getFieldDecorator('vehicleId', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: selectDetails ? selectDetails.vehicleId : '',
                        })(
                          <SearchSelect
                            dataUrl="tms/tms-etc/selectEtcVehicle"
                            url="tms/tms-etc/selectVehicleView_s" // selectedData只只有id时需要传url
                            selectedData={cars} // 选中值
                            multiple={false} // 是否多选
                            showValue="cartPlateOneNo"
                            searchName="cartPlate"
                            columns={columns1} // 表格展示列
                            onChange={this.getValue} // 获取选中值
                            scrollX={480}
                            id="etcList_2"
                            disabled={disabled}
                          />
                        )}
                      </Form.Item>
                    </Col>
                    <Col {..._col}>
                      <Form.Item label="所属公司">
                        {getFieldDecorator('ownCompanyName', {
                          initialValue: ownCompany
                            ? ownCompany
                            : selectDetails && selectDetails.ownCompanyName,
                        })(<Input placeholder="请输入" disabled={true} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={_gutter}>
                    <Col {..._col}>
                      <Form.Item label="剩余金额">
                        {getFieldDecorator('balance', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: selectDetails ? selectDetails.balance : '',
                        })(
                          <Input
                            placeholder="请输入"
                            addonBefore={prefixSelector}
                            style={{ width: '100%' }}
                            disabled={disabled || checkDisabled}
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={_gutter}>
                    <Col {..._row}>
                      <Form.Item label="备注">
                        {getFieldDecorator('remarks', {
                          initialValue: selectDetails ? selectDetails.remarks : '',
                        })(<TextArea placeholder="请输入" disabled={disabled} rows={4} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  {/* <Row gutter={_gutter}>
                    <Col {..._row}>
                      <Form.Item label="票据">
                        {getFieldDecorator('fileTokens')(
                          <AntdUpload
                            fileList={fileList}
                            onRemove={this.onRemove}
                            handleChange={this.handleChange}
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row> */}
                </Form>
              </div>
            </Panel>
          </Collapse>
        </PageHeaderWrapper>
      </div>
    );
  }
}
